package org.jeecg.modules.alarm.handler.impl;

import com.zhouwr.common.network.CommonConnectContext;
import io.netty.channel.ChannelFuture;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.alarm.entity.ActuatorDataForward;
import org.jeecg.modules.alarm.handler.IActuatorHandle;
import org.jeecg.modules.alarm.service.IActuatorDataForwardService;
import org.jeecg.modules.network.entity.NetworkService;
import org.jeecg.modules.network.network.NetworkConnectStore;
import org.jeecg.modules.network.service.INetworkServiceService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.Map;

/**
 * @program: forallcn-iotps
 * @description:
 * @author: zhouwr
 * @create: 2021-06-17 09:24
 * @version：1.0
 **/
public class DataForwardHandle implements IActuatorHandle {
    @Autowired
    private IActuatorDataForwardService dataForwardService;
    @Autowired
    private INetworkServiceService networkService;
    private ChannelFuture future;

    public DataForwardHandle() {
        this.dataForwardService = (IActuatorDataForwardService) SpringContextUtils.getBean(IActuatorDataForwardService.class);
        this.networkService = (INetworkServiceService) SpringContextUtils.getBean(INetworkServiceService.class);
    }

    @Override
    public boolean invoke(String actuatorId, Map<String, Object> dataMap) {
        try {
            ActuatorDataForward dataForward = dataForwardService.getById(actuatorId);
            NetworkService network = networkService.getById(dataForward.getNetworkServiceId());

            Arrays.stream(dataForward.getForwardReceivers().split(",")).peek(receiver -> {
                CommonConnectContext connectContext = NetworkConnectStore.getNetworkConnectMap().get(receiver);
                try {
                    future = connectContext.getChannelHandlerContext().channel().writeAndFlush(dataMap).await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return future.isDone();
    }
}
